package com.mazaiting.redis.manager;

import com.googlecode.aviator.AviatorEvaluator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.lang.NonNull;
import org.springframework.util.StringUtils;

import java.time.Duration;

/**
 * 自定义缓存时间管理者
 *
 * @author mazaiting
 * @create_time 2022/9/5 15:39
 */
public class TtlRedisCacheManager extends RedisCacheManager {

    /**
     * 日志工具
     */
    private final Logger logger = LoggerFactory.getLogger(TtlRedisCacheManager.class);

    public TtlRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    @NonNull
    @Override
    protected RedisCache createRedisCache(@NonNull String name, RedisCacheConfiguration cacheConfig) {
        try {
            // 如果包含=, 则第 0 位是键名, 第 1 位是缓存时间
            if (name.contains("=")) {
                String[] cells = StringUtils.delimitedListToStringArray(name, "=");
                // 赋值键名
                name = cells[0];
                if (cells.length > 1) {
                    // 缓存时长
                    long ttl = Long.parseLong(String.valueOf(AviatorEvaluator.execute(cells[1])));
                    // 默认参数时间为秒
                    cacheConfig = cacheConfig.entryTtl(Duration.ofSeconds(ttl));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("自定义缓存时间配置异常: " + name);
        }
        return super.createRedisCache(name, cacheConfig);
    }
}
